﻿using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Net.Http.Headers;

namespace LeoGemini.Service.Infrastructure.Extension
{
    public static partial class Extensions
    {
        public static async Task SaveFile(this HttpRequest request, string path)
        {
            var boundary = HeaderUtilities.RemoveQuotes(MediaTypeHeaderValue.Parse(request.ContentType).Boundary).Value;
            var reader = new MultipartReader(boundary, request.Body);
            
            MultipartSection section;
            while ((section = await reader.ReadNextSectionAsync()) != null)
            {
                var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition);
                if (hasContentDispositionHeader)
                {
                    var trustedFileNameForFileStorage = Path.GetRandomFileName();
                    await section.Body.WriteToPathAsync(Path.Combine(path, trustedFileNameForFileStorage));
                }
            }
        }
    }
}